import 'package:flutter/foundation.dart';
import '../mongo_service.dart';
import '../project.dart';
import 'package:logger/logger.dart';

class ProjectProvider with ChangeNotifier {
  List<Project> _projects = [];
  List<Project> _filteredProjects = [];
  final MongoService _mongoService = MongoService();
  final Logger _logger = Logger();
  bool _isConnected = false;
  List<String> _owners = [];
  String _sortBy = 'sequence';
  bool _isAscending = true;

  List<Project> get projects => _filteredProjects;
  bool get isConnected => _isConnected;
  List<String> get owners => _owners;

  ProjectProvider() {
    _filteredProjects = List.from(_projects);
  }

  Future<void> connect(String connectionString) async {
    try {
      await _mongoService.connect(connectionString, fetchProjects);
      _isConnected = true;
      notifyListeners();
    } catch (e) {
      _isConnected = false;
      _logger.e('数据库连接失败: $e');
      rethrow;
    }
  }

  Future<void> disconnect() async {
    try {
      await _mongoService.close();
      _isConnected = false;
      _projects = [];
      _filteredProjects = [];
      _owners = [];
      notifyListeners();
    } catch (e) {
      _logger.e('断开数据库失败: $e');
      rethrow;
    }
  }

  Future<void> fetchProjects() async {
    try {
      final data = await _mongoService.getProjects();
      _projects = data.map((json) => Project.fromJson(json)).toList();
      _filteredProjects = List.from(_projects);
      _owners = _projects
          .map((p) => [p.businessManager, p.softwareManager, p.projectManager])
          .expand((i) => i)
          .where((owner) => owner.isNotEmpty)
          .toSet()
          .toList();
      sortProjects(_sortBy, _isAscending);
      notifyListeners();
      _logger.i('成功获取 ${_projects.length} 个项目，负责人列表: ${_owners.length} 个');
    } catch (e) {
      _logger.e('获取项目失败: $e');
      rethrow;
    }
  }

  void searchProjects(String query) {
    if (query.isEmpty) {
      _filteredProjects = List.from(_projects);
    } else {
      _filteredProjects = _projects.where((project) {
        return project.productCategory.toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            project.assemblyBOM.toLowerCase().contains(query.toLowerCase()) ||
            project.softwareDetails.toLowerCase().contains(query.toLowerCase());
      }).toList();
    }
    sortProjects(_sortBy, _isAscending);
    notifyListeners();
    _logger.i('搜索项目: 查询="$query", 结果=${_filteredProjects.length} 个');
  }

  void filterProjects({
    String? productCategory,
    String? softwareStatus,
    String? owner,
  }) {
    _filteredProjects = _projects.where((project) {
      bool matches = true;
      if (productCategory != null && productCategory != '所有') {
        matches = matches && project.productCategory == productCategory;
      }
      if (softwareStatus != null && softwareStatus != '所有') {
        matches = matches && project.softwareStatus == softwareStatus;
      }
      if (owner != null && owner.isNotEmpty) {
        matches =
            matches &&
            (project.businessManager == owner ||
                project.softwareManager == owner ||
                project.projectManager == owner);
      }
      return matches;
    }).toList();
    sortProjects(_sortBy, _isAscending);
    notifyListeners();
    _logger.i(
      '筛选项目: 产品分类=$productCategory, 软件状态=$softwareStatus, 负责人=$owner, 结果=${_filteredProjects.length} 个',
    );
  }

  void sortProjects(String sortBy, bool isAscending) {
    _filteredProjects.sort((a, b) {
      int compare;
      switch (sortBy) {
        case 'estimatedTime':
          compare = a.estimatedTime.compareTo(b.estimatedTime);
          break;
        case 'testTime':
          compare = a.testTime.compareTo(b.testTime);
          break;
        case 'sequence':
        default:
          compare = a.sequence.compareTo(b.sequence);
          break;
      }
      return isAscending ? compare : -compare;
    });
    _sortBy = sortBy;
    _isAscending = isAscending;
    notifyListeners();
  }
}
